package com.financing.wap.web.controller.api;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.util.HSSFColor.BLACK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.ImgUtil;
import com.financing.wap.common.QRCodeUtil;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.RegisterDTO;
import com.financing.wap.dto.ShopperUserInfoDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IShopperUserInfoService;
import com.financing.wap.util.AliyunOssUtil;
import com.financing.wap.util.Constants;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

/**
 * 二维码api
 * 
 * @author lisu
 *
 */
@Controller("QRcodeController")
@RequestMapping("/api/QRcode")
public class QRCodeController extends BaseController {

	Logger logger = Logger.getLogger(getClass());

	/**
	 * 二维码-用户活动推广URL
	 */
	public static final String QRCODE_USER_PROMOTION = PropertiesUtils.getValue("qrCode_user_promotion");

	/**
	 * 用户邀请链接-pc
	 */
	public static final String USER_INVITATION_LINK_PC = PropertiesUtils.getValue("user_invitation_link_pc");

	/**
	 * 用户邀请链接-wap
	 */
	public static final String USER_INVITATION_LINK_WAP = PropertiesUtils.getValue("user_invitation_link_wap");

	/**
	 * 二维码-手机端pevc产品详情
	 */
	public static final String QRCODE_PEVCPRODUCT_DETAIL = PropertiesUtils.getValue("qrCode_pevcproduct_detail");

	/**
	 * 二维码-手机端信托资管产品详情
	 */
	public static final String QRCODE_XTZGPRODUCT_DETAIL = PropertiesUtils.getValue("qrCode_xtzgproduct_detail");

	/**
	 * 二维码-手机端店铺二维码分享
	 */
	public static final String QRCODE_SHOPQRCODE = PropertiesUtils.getValue("shop_share_qrcode");
	
	/**
	 * 产品图文二维码分享链接 - 私募
	 */
	public static final String PROD_QECODE_SIMU = PropertiesUtils.getValue("prod_qrcode_simu");
	
	/**
	 * 产品图文二维码分享链接 - 其他类型
	 */
	public static final String PROD_QECODE_XTZG = PropertiesUtils.getValue("prod_qrcode_xtzg");
	
	/**
	 * 产品图文二维码分享链接 - 股权基金
	 */
	public static final String PROD_QECODE_PEVC = PropertiesUtils.getValue("prod_qrcode_pevc");
	
	/**
	 * 产品图文二维码分享链接 - 自营产品
	 */
	public static final String PROD_QECODE_SELF = PropertiesUtils.getValue("prod_qrcode_self");

	public Map<String, String> map = new HashMap<String, String>();

	@Autowired
	private IShopperUserInfoService shopperUserInfoService;

	/**
	 * 生成用户活动推广二维码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/userpromotion")
	public void userPromotion(HttpServletRequest request, RegisterDTO register,
			HttpServletResponse response) throws IOException {
		logger.info("In QRCodeController userPromotion begin!");
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String faId = loginUser.getId();
		String user_promotion = QRCODE_USER_PROMOTION;
		logger.info("In QRCodeController  user_promotion:"+user_promotion);
		user_promotion = user_promotion.replace("MID", faId.toString());
		user_promotion = user_promotion.replace("MCODE", StringUtil.encryptCardNumber(loginUser.getLoginName()));
		logger.info("In QRCodeController  user_promotion:"+user_promotion);
		try {
			QRCodeUtil.encoderQRCode(user_promotion, response.getOutputStream());
			logger.info("In QRCodeController userPromotion end!");
		} catch (Exception e) {
			logger.error("In QRCodeController userPromotio error",e);
		}
		return ;
	}

	/**
	 * 二维码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/m2productDetail")
	public void m2productDetail(HttpServletRequest request, 
			HttpServletResponse response,String type) throws IOException {
		logger.info("In QRCodeController  m2productDetail");
		//pevc
		String qrcode_product_detail = map.get(type==null?"pevc":type);
		logger.info("In QRCodeController  qrcode_product_detail:"+qrcode_product_detail);
		String p_code=request.getParameter("p_code");
		qrcode_product_detail=qrcode_product_detail.replace("{pcode}", p_code);
		logger.info("update QRCodeController  qrcode_product_detail:"+qrcode_product_detail);

		try {
			QRCodeUtil.encoderQRCode(qrcode_product_detail, response.getOutputStream());
			logger.info("In QRCodeController qrcode_product_detail end!");
		} catch (Exception e) {
			logger.error("In QRCodeController qrcode_product_detail error",e);
		}
		return ;
	}
	@PostConstruct
	public void init(){
		logger.info("update QRCodeController  initQRCode:");
		map.put("pevc", QRCODE_PEVCPRODUCT_DETAIL);
		map.put("xtzg", QRCODE_XTZGPRODUCT_DETAIL);
	}
	/**
	 * 生成用户活动推广二维码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/userInvitationLink")
	public void UserInvitationLink(HttpServletRequest request, RegisterDTO register,
			HttpServletResponse response) throws IOException {
		logger.info("In QRCodeController UserInvitationLink begin!");
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前用户ID
		String userId = loginUser.getLoginName();		//判断入口
		//验证码校验
		String platformtype = request.getParameter(Constants._PT);
		String UserInvitationLink = null;
		try {
			//1pc,2app ,默认pc
			if(StringUtils.isEmpty(platformtype)||Constants._PT_pc.equals(platformtype)){
				UserInvitationLink = USER_INVITATION_LINK_PC;
				UserInvitationLink = UserInvitationLink.replace("SOURCE_MOBILE", userId);
				QRCodeUtil.encoderQRCode(UserInvitationLink, response.getOutputStream(),264,264);
			}else if(Constants._PT_wap.equals(platformtype)){
				UserInvitationLink = USER_INVITATION_LINK_WAP;
				UserInvitationLink = UserInvitationLink.replace("SOURCE_MOBILE", userId);
				QRCodeUtil.encoderQRCode(UserInvitationLink, response.getOutputStream(),150,150);
			}
			logger.info("In QRCodeController UserInvitationLink end!");
		} catch (Exception e) {
			logger.error("In QRCodeController UserInvitationLink error",e);
		}
		return ;
	}

	/**
	 * 生成产品图文二维码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/prodqrcode")
	public void prodqrcode(HttpServletRequest request, RegisterDTO register,
			HttpServletResponse response) throws IOException {
		logger.info("In QRCodeController UserInvitationLink begin!");
		
		String proid = request.getParameter("proid");
		String protype = request.getParameter("protype");
		
		//当前用户ID
		String userPhone = request.getParameter("userPhone");
		String prodlink = null;//产品链接
		try {
			//1pc,2app ,默认pc
			if(StringUtils.equals(protype, "simu")){//私募
				prodlink = PROD_QECODE_SIMU;
			} else if(StringUtils.equals(protype, "pevc")) {//股权基金
				prodlink = PROD_QECODE_PEVC;
			} else if(StringUtils.equals(protype, "xtzg")) {//其他
				prodlink = PROD_QECODE_XTZG;
			} else if(StringUtils.equals(protype, "self")) {//自营
				prodlink = PROD_QECODE_SELF;
			}
			
			prodlink = prodlink.replace("SOURCE_PROID", proid);
			prodlink = prodlink.replace("SOURCE_MOBILE", userPhone);
			QRCodeUtil.encoderQRCodeNoBorder(prodlink, response.getOutputStream(),200,200);
			logger.info("In QRCodeController UserInvitationLink end!");
		} catch (Exception e) {
			logger.error("In QRCodeController UserInvitationLink error",e);
		}
		return ;
	}
	
	/**
	 * 生产店铺二维码
	 * 
	 * @param request
	 * @param register
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/userShopErweima")
	@ResponseBody
	public ResultMap userShopErweima(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.info("In QRCodeController userShopErweima begin!");

		ResultMap result = new ResultMap();
		try {
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();

			ShopperUserInfoDTO shopperUserInfo=new ShopperUserInfoDTO();
			//用户id
			shopperUserInfo.setUserId(loginUser.getId());
			ShopperUserInfoDTO dto = shopperUserInfoService.queryListGetFirst(shopperUserInfo);

			String staticbaseUrl = request.getParameter("staticbaseUrl");//服务器url
			String baseUrl = request.getParameter("baseUrl");//服务器url
			String isuseoss = request.getParameter("isuseoss");//是否启用oss 0：是 1:否
//			String baseUrl = "http://licaishi.superfa.cn";//服务器url
			String backUrl = dto.getShopBackground();//海报顶部背景url
			String headUrl = dto.getUserHeadImg();//海报头像背景url
			String text1 = dto.getPersonalizedSignature();//店铺简介
			String text2 = dto.getUserName();

//			if(StringUtils.isEmpty(backUrl)) {
//				backUrl = baseUrl+"/upload/faUser/shop/common/cope_img.jpg";
//			} else {
//				backUrl = baseUrl+backUrl;
//			}
//			if(StringUtils.isEmpty(headUrl)) {
//				headUrl = baseUrl+"/upload/faUser/shop/common/touxiang.jpg";
//			} else {
//				if(headUrl.indexOf("http://wx.qlogo.cn/") < 0) {
//					headUrl = baseUrl+headUrl;
//				}
//			}

			String url = QRCODE_SHOPQRCODE; 
			url =url.replace("MPHONE", loginUser.getLoginName());
			//			QRCodeUtil.encoderQRCode(url, response.getOutputStream(),300,300);
//			String format = "png";   
			BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, 300, 300);
			
			String fileBaseDir = PropertiesUtils.getValue("fileBaseDir");
			StringBuffer fileFullPath = new StringBuffer();
			fileFullPath.append(fileBaseDir)
			.append("/upload")
			.append("/faUser")
			.append("/shop")
			.append("/")
			.append(loginUser.getId()+"qrcode.png");
			String filePath = org.apache.commons.lang.StringUtils.replace(fileFullPath.toString(),fileBaseDir+"/","");
			
			System.out.println("===========极简二维码==========");
			System.out.println(filePath);
			
			
			String qrcodeUrl = "";
			if(StringUtils.equals(isuseoss, "0")) {
				if(StringUtils.isEmpty(backUrl)) {
					backUrl = staticbaseUrl+"/upload/faUser/shop/common/cope_img.jpg";
				} else {
					backUrl = staticbaseUrl+backUrl;
				}
				if(StringUtils.isEmpty(headUrl)) {
					headUrl = staticbaseUrl+"/upload/faUser/shop/common/touxiang.jpg";
				} else {
					if(headUrl.indexOf("http://wx.qlogo.cn/") < 0) {
						headUrl = staticbaseUrl+headUrl;
					}
				}
				
				BufferedImage buffimg = toBufferedImage(bitMatrix);
				ByteArrayOutputStream bs =new ByteArrayOutputStream();
				ImageOutputStream imOut =ImageIO.createImageOutputStream(bs);
				ImageIO.write(buffimg,"png",imOut);
				InputStream is =new ByteArrayInputStream(bs.toByteArray());
				
				AliyunOssUtil.writeFile(is, filePath);
				
				qrcodeUrl = staticbaseUrl+"/"+filePath;//二维码地址
			} else {
				String qecodeFilepath = PropertiesUtils.getValue("fileBaseDir")+"/upload/faUser/shop/"+loginUser.getId()+"qrcode.png";
				MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(qecodeFilepath));
				
				if(StringUtils.isEmpty(backUrl)) {
					backUrl = baseUrl+"/upload/faUser/shop/common/cope_img.jpg";
				} else {
					backUrl = baseUrl+backUrl;
				}
				if(StringUtils.isEmpty(headUrl)) {
					headUrl = baseUrl+"/upload/faUser/shop/common/touxiang.jpg";
				} else {
					if(headUrl.indexOf("http://wx.qlogo.cn/") < 0) {
						headUrl = baseUrl+headUrl;
					}
				}
				
				qrcodeUrl = baseUrl+"/upload/faUser/shop/"+loginUser.getId()+"qrcode.png";//二维码地址
			}

			//绘制二维码海报
			String qrcodeHbUrl = baseUrl+ImgUtil.makeImg(backUrl, headUrl, text1, qrcodeUrl, text2, loginUser.getId()+"qrcode_hb", isuseoss);

			System.out.println("===========二维码海报==========");
			System.out.println("backUrl:"+backUrl);
			System.out.println("headUrl:"+headUrl);
			System.out.println("qrcodeUrl:"+qrcodeUrl);

			result.setAttribute("qrcodeUrl", qrcodeUrl);
			result.setAttribute("qrcodeHbUrl", qrcodeHbUrl);
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			logger.info("In QRCodeController userShopErweima end!");
		} catch (Exception e) {
			System.out.println("===========二维码海报:Exception==========");
			e.printStackTrace();
			logger.error("In QRCodeController userShopErweima error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	public static BufferedImage toBufferedImage(BitMatrix matrix) {
		//二维码颜色  
	    int BLACK = 0xFF000000;  
	    //二维码颜色  
	    int WHITE = 0xFFFFFFFF;
		
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
	
}
